<template>
  <div class="createPost-container">
    <el-steps :active="index" v-if="!isReport && !isTarget" finish-status="success" simple style="margin-top: 20px">
      <el-step title="填写基础信息"></el-step>
      <el-step title="选择处理人"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <el-steps :active="index" v-else-if="isReport && !isTarget" finish-status="success" simple style="margin-top: 20px">
      <el-step title="填写基础信息"></el-step>
      <el-step title="数据上报类型"></el-step>
      <el-step title="选择处理人"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <el-steps :active="index" v-else-if="!isReport && isTarget" finish-status="success" simple style="margin-top: 20px">
      <el-step title="填写基础信息"></el-step>
      <el-step title="指标体系"></el-step>
      <!-- <el-step title="选择处理人"></el-step> -->
      <el-step title="完成"></el-step>
    </el-steps>
    <el-steps :active="index" v-else="isReport && isTarget" finish-status="success" simple style="margin-top: 20px">
      <el-step title="填写基础信息"></el-step>
      <el-step title="数据上报类型"></el-step>
      <el-step title="指标体系"></el-step>
      <!-- <el-step title="选择处理人"></el-step> -->
      <el-step title="完成"></el-step>
    </el-steps>

    <baseInfo ref="baseInfo" v-show="index === 0" :isEdit="isEdit" :initData="initData" :preFileList="preFileList"
      @changeFiles="changeFiles" @changeReportType="changeReportType" @changeRelate="changeRelate" />
    <template v-if="isReport && !isTarget">
      <reportType ref="reportType" :reportType="b_reportType" :reportTitle="baseInfoTitle" v-show="index === 1" />
    </template>
    <template v-if="!isReport && isTarget">
      <targetInfo ref="targetInfo" :isEdit="isEdit" :initId="targetId" v-show="index === 1" @updateUsers="updateUsers"
        @initUsers="initUsers" @setIndexObj="getIndexObj" />
    </template>
    <template v-if="isReport && isTarget">
      <reportType ref="reportType" :reportType="b_reportType" :reportTitle="baseInfoTitle" v-show="index === 1" />
      <targetInfo ref="targetInfo" :isEdit="isEdit" :initId="targetId" v-show="index === 2" @updateUsers="updateUsers"
        @initUsers="initUsers" @setIndexObj="getIndexObj" />
    </template>
    <userManager 
      ref="userManager" 
      v-show="index === stepsLevel && !isTarget" 
      :relateUsers="relateUsers" 
      :showSaveSelectedUser="false"
      style="margin: 20px"
    />
    <result-pager v-show="index === 4">
      <template slot="btn">
        <el-button type="primary" @click="handReback">返回列表</el-button>
        <el-button @click="handPreview">查看任务</el-button>
      </template>
    </result-pager>
    <!-- <template v-if="isReport && !isTarget">
      <reportType ref="reportType" v-show="index === 1" />
    </template> -->
    <!-- <template v-if="!isReport && !isTarget">
      <baseInfo ref="baseInfo" v-show="index === 0" :isEdit="isEdit" @changeReportType="changeReportType"/>
      <userManager ref="userManager" v-show="index === 1" />
    </template>
    <template v-if="!isReport && !isTarget">
      <baseInfo ref="baseInfo" v-show="index === 0" :isEdit="isEdit" @changeReportType="changeReportType"/>
      <userManager ref="userManager" v-show="index === 1" />
    </template> -->
    <div class="footer">
      <el-button v-if="index !== 0 && index !== 4" size="small" @click="preStep">上一步</el-button>
      <el-button v-if="index < stepsLevel" type="primary" size="small" @click="nextStep">下一步</el-button>
      <el-button v-if="index == stepsLevel" type="primary" size="small" @click="submitForm">提交</el-button>
    </div>
    <div class="dialog" v-show="isShowDialog">
      <div class="content">
        <div class="text">文件上传进度</div>
        <el-progress :percentage="uploadPress" :stroke-width='10' class="process"></el-progress>
      </div>
    </div>
  </div>
</template>
<script>
  import {
    postCreateTask,
    getTaskInfo,
    delTask,
    createIndex
  } from '@/api/work.js'
  import {
    getTable,
    delTable,
    getQuestion,
    delQuestion
  } from '@/api/question.js'
  import {
    parseTime,
    fileJoinBaseUrl
  } from '@/utils/index'
  import {
    createQuestion,
    createTableReport
  } from '@/api/question.js'
  import axios from 'axios'
  import Cookies from 'js-cookie'
  export default {
    name: 'publishTask',
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    components: {
      baseInfo: () => import('../components/baseInfo.vue'),
      targetInfo: () => import('../components/targetInfo.vue'),
      reportType: () => import('../components/reportType.vue'),
      userManager: () => import('../components/userManager.vue'),
      resultPager: () => import('@/views/markSys/components/ResultPager'),
    },
    computed: {
      stepsLevel() {
        if (!this.isReport && !this.isTarget || (!this.isReport && this.isTarget)) {
          return 1
        } else if ((this.isReport && !this.isTarget)) {
          return 2
        } else {
          return 3
        }
        return 0
      }
    },
    data() {
      return {
        index: 0,
        uploadPress: 0,
        taskId: null,
        parentId: null,
        reportId: null,
        baseInfoTitle: '', // 任务标题
        targetId: null, // 指标id
        isReport: false,
        isTarget: false,
        initData: null,
        fileList: [],
        preFileList: [],
        b_reportType: '通知',
        relateUsers: [], // 关联指标人员
        // stepsLevel: 1,
        isShowDialog: false,
        isChangeIndex: false,
        indexObj: null // 选择指标对象
      }
    },
    created() {
      // 初始化父任务ID
      const param = this.$route.params
      if (param) {
        this.parentId = param.parent
        if (param.initData && param.initData.title) {
          const {
            title,
            body,
            data_type,
            classify,
            end_time,
            taskFile
          } = param.initData
          this.initData = {
            title: title,
            content: body,
            end_time: end_time,
            reportType: data_type,
            taskType: classify,
            fileList: fileJoinBaseUrl(taskFile)
          }
          this.isReport = (data_type === '文件上传' || data_type === '通知') ? false : true
          this.b_reportType = data_type
        }
      }
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.taskId = id
        this.fetchData(id)
      }
    },
    methods: {
      fetchData(id) {
        let that = this
        // 获取基础填信息
        getTaskInfo(id).then(res => {
          const result = res.data
          const baseInfo = {
            title: result.title,
            content: result.body,
            utilTime: result.end_time,
            taskType: result.classify,
            important: result.emergency_level,
            isRelate: result.target ? true : false,
            reportType: result.data_type
          }
          // 是否显示数据填报、指标信息
          this.isReport = (result.data_type === '文件上传' || result.data_type === '通知') ? false : true
          this.isTarget = result.target ? true : false
          this.preFileList = fileJoinBaseUrl(result.taskFile) // 任务附件文件列表

          this.$refs.baseInfo.postForm = baseInfo // 填充基础信息

          this.b_reportType = result.data_type //填充上报类型
          this.targetId = result.target // 指标信息ID
          // const reportTpye = {
          //   reportType: result.data_type,
          //   type: '必填',
          //   fileNum: result.limit_file
          // }
          // this.$refs.reportType.postForm = reportTpye
          // this.$refs.reportType.isRelate = result.target ? true : false
          // this.$refs.reportType.markVaule = result.target

          this.relateUsers = this.transformObject(result.user, result.username)
          // 判断填报类型
          if (result.data_type === '表格填报') {
            // 获取填报表格信息
            getTable({
              task: id
            }).then(res => {
              const data = res.data.results[0]
              this.reportId = data.id
              if (data.parent.length) {
                const table = []
                data.parent.forEach(item => {
                  const childs = []
                  item.child.forEach(e => {
                    childs.push({
                      name: e.name,
                      status: e.status
                    })
                  })
                  const temp = {
                    name: item.name,
                    status: item.status,
                    child: childs
                  }
                  table.push(temp)
                })
                this.$nextTick(() => {
                  this.$refs.reportType.singleTable = table
                })
              }
              this.$refs.reportType.tableType = data.type
            })
          }
          if (result.data_type == '测评问卷') {
            // 获取问卷信息
            getQuestion({
              task: id
            }).then(res => {
              const result = res.data.results[0]
              this.reportId = result.id
              if (result.item.length) {
                const ques = []
                result.item.forEach(item => {
                  const temp = {
                    title: item.title,
                    qtype: item.qtype,
                    choice: item.choice
                  }
                  ques.push(temp)
                })
                this.$refs.reportType.questionName = result.caption
                this.$refs.reportType.isFade = result.is_anonymous ? 'True' : 'False'
                this.$refs.reportType.question = ques
              }
            })
          }
        })
      },
      // 跳转任务列表
      handReback() {
        this.$router.push({
          name: 'Manager'
        })
      },
      handPreview() {
        this.$router.push({
          name: 'PreviewTask',
          params: {
            targetId: this.taskId,
            isHand: true
          }
        })
      },
      // 键值映射
      transformObject(keyArr, valueArr) {
        let arr = []
        keyArr.forEach((v, i) => {
          arr.push({
            id: keyArr[i],
            first_name: valueArr[i]
          })
        })
        return arr;
      },
      // 文件选择组件
      changeFiles(val) {
        this.fileList = val
      },
      // 获取选择指标对象
      getIndexObj(obj, id) {
        this.indexObj = obj
        if (id) {
          this.isChangeIndex = (id && obj.id !== id) ? true : false
        }
      },
      initUsers(val) {
        this.relateUsers = val
      },
      // 更新人员数量
      updateUsers(val) {
        this.relateUsers = val
      },
      changeReportType(val) {
        this.b_reportType = val
        this.isReport =  (val === '文件上传' || val === '通知') ? false : true
      },
      changeRelate(val) {
        this.isTarget = val
      },
      nextStep() {
        this.baseInfoTitle = this.$refs.baseInfo && this.$refs.baseInfo.postForm.title
        if (this.index++ > 1) this.active = 0;
      },
      preStep() {
        if (this.index-- < 0) this.active = 1;
      },
      getChildData() {
      },
      postReport(taskId, type, title, tableData, quesData, questionName, isFade) {
        var {
              postForm,
              tableTitle,
              tableType,
              singleTable,
              question,
              questionName,
              isFade,
              markVaule
            } = this.$refs.reportType
        const para = {
          task: taskId,
          title: tableTitle,
          type: tableType,
          item: singleTable
        }
        if (type === '表格填报') {
          createTableReport(para).then(res => {
            // if(res && this.reportId){
            //   delTable(this.reportId).then(res=>{})
            // }
          })
        } else {
          const quesPara = {
            task: taskId,
            caption: questionName,
            is_anonymous: isFade,
            item: quesData
          }
          createQuestion(quesPara).then(res => {
            // if(res && this.reportId){
            //     delQuestion(this.reportId).then(res=>{})
            //   }
          })
        }
      },
      async submitForm() {
        var targetId = null
        var checkUser = null
        const {
          title,
          content,
          utilTime,
          taskType,
          important
        } = this.$refs.baseInfo.postForm

        // 如果指标已使用
          if (this.isTarget) {
            if ((!this.isEdit && this.indexObj.is_used) || (this.isEdit && this.isChangeIndex && this.indexObj
                .is_used)) {
              // 创建新指标
              const result = await createIndex(this.indexObj)
              targetId = result.data.id
            } else {
              targetId = this.indexObj.id
            }
          }
          if (this.isTarget) {
            if (this.relateUsers.length === 0) {
              this.$message.warning('请选择指标安排人员')
              return
            }
            checkUser = this.relateUsers
          } else {
            checkUser = this.$refs.userManager.sureUsersList
          }
          if (this.isReport) {
            var {
              postForm,
              singleTable,
              question,
              questionName,
              isFade,
              markVaule
            } = this.$refs.reportType
          }
          const param = {
            "file": this.fileList,
            "body": content,
            "title": title,
            "end_time": parseTime(new Date(utilTime)),
            "emergency_level": important,
            'limit_file': 0,
            'data_type': this.b_reportType,
            "classify": taskType,
            "user": checkUser,
            "finish_approval": 'True',
            "is_edit": 'True',
            "is_normal": 'True',
          }
          // 是否关联指标ID
          if (targetId) {
            param['target'] = targetId
          }
          // return
          // 是否添加父任务ID
          if (this.parentId) {
            param.parent = this.parentId
          }
        if (!title || !content) {
          this.$message({
            type: 'warning',
            message: '请填写任务标题和详细说明!'
          });
          return
        }
        if (!utilTime) {
          this.$message({
            type: 'warning',
            message: '请选择上报截至时间!'
          });
          return
        }
        if (!taskType) {
          this.$message({
            type: 'warning',
            message: '请选择任务类别!'
          });
          return
        }
        
        if ((this.b_reportType === '表格填报') && !singleTable.every(e => e.name)) {
          this.$message({
            type: 'warning',
            message: '请填写表格填报表项内容!'
          });
          return
        }
        if (this.b_reportType === '测评问卷' && !question.every(e => e.title)) {
          this.$message({
            type: 'warning',
            message: '请完善问卷信息!'
          });
          return
        }
        if (this.b_reportType === '测评问卷' && !questionName) {
          this.$message({
            type: 'warning',
            message: '请填写问卷标题!'
          });
          return
        }
        this.$confirm('即将提交任务数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          
          
          var form = new FormData()
          for (const key of Object.keys(param)) {
            if (key !== 'file' && key !== 'user') {
              form.append(key, param[key])
            }
          }
          if (param.user && param.user.length > 0) {
            for (let i = 0; i < param['user'].length; i++) {
              form.append('user', param['user'][i].id)
            }
          }
          if (param.file.length > 0) {
            for (let i = 0; i < param['file'].length; i++) {
              form.append('file', param['file'][i].raw)
            }
          }
          var config = {
            headers: {
              'Content-Type': 'multipart/form-data',
              'X-CSRFToken': Cookies.get('csrftoken')
            },
            onUploadProgress: progressEvent => {
              var complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
              this.uploadPress = Number(complete)
            }
          }

          if (this.fileList.length) {
            this.isShowDialog = true
          }
          if (this.isEdit) {
            axios.patch(`/api/Work/Task/${this.taskId}/`,
              form, config).then((res) => {
              this.uploadPress = 0
              if (res.data) {
                this.isShowDialog = false
                const taskId = res.data.id
                this.handResult(taskId, title, singleTable, question, questionName, isFade)
              }
            }).catch(res => {
              this.isShowDialog = false
            });
          } else {
            axios.post(`/api/Work/Task/`,
              form, config).then((res) => {
              this.uploadPress = 0
              if (res.data) {
                this.isShowDialog = false
                this.taskId = res.data.id
                this.handResult(this.taskId, title, singleTable, question, questionName, isFade)
              }
            })
          }
        });
      },
      handResult(taskId, title, singleTable, question, questionName, isFade) {
        if (this.b_reportType !== '文件上传' && this.b_reportType !== '通知') {
          singleTable.forEach(item => {
            if (item.child.every(e => !e)) {
              item.child = []
            }
          })
          this.postReport(taskId, this.b_reportType, title, singleTable, question, questionName, isFade)
        }
        // const name = this.isEdit ? '编辑':'发布'
        // this.$notify({
        //   title: '成功',
        //   message: `${name}任务成功`,
        //   type: 'success'
        // });
        this.index = 4
        // if(this.isEdit){
        //   delTask(this.taskId).then(res=>{

        //   })
        // }
        // this.$router.push({name:'TaskCenter'})
      }
    },
    // beforeRouteLeave (to, from, next) {
    // // 这里需要elementui的支持，如果使用其他界面组件自行替换即可
    // this.$confirm('正在离开本页面，本页面内所有未保存数据都会丢失', '警告', {
    //    confirmButtonText: '确定',
    //    cancelButtonText: '取消',
    //    type: 'warning'
    //  }).then(() => {
    //    // 正常跳转
    //    next()
    //  }).catch(() => {
    //    // 如果取消跳转地址栏会变化，这时保持地址栏不变
    //    window.history.go(1)
    //  })

    // }
  }

</script>
<style lang="scss" scoped>
  .createPost-container {

    /* position: relative; */
    /* .main{
      height: calc(100vh - 77px);
    } */
    .footer {
      display: flex;
      justify-content: center;
      margin-bottom: 10px;

      >.el-button {
        margin: 0 6px;
      }
    }

    .dialog {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, .5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 999;

      .content {
        width: 300px;
        height: 80px;
        background: #fff;

        .text {
          text-align: center;
          padding: 10px 0;
        }

        .process {
          margin-left: 20px;
        }
      }
    }
  }

</style>
